package com.yupi.springbootinit.RabbitMQ;

import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.manager.ChartManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.enums.StringEnum;
import com.yupi.springbootinit.service.ChartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class BiConsumer {
    @Resource
    private ChartService chartService;
    @Resource
    private ChartManager chartManager;
    @RabbitListener(queues = {BIMQStringEnum.BI_QUEUE},concurrency = "2")
    public void receive(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliverTag, String message) throws Exception {
        log.info("从消息队列中线程{}接收到的消息{}",channel.getChannelNumber(), message);
        Chart chartById = chartService.getById(message);
        String csvData = chartById.getChartData();
        String chartType = chartById.getChartType();
        String goal = chartById.getGoal();
        String q;
        if (StringUtils.isNotBlank(chartType))
            q = csvData + "图表类型:" + chartType + "\n" + StringEnum.aiEnd;
        else q = csvData + StringEnum.aiEnd;

        //校验提交的任务的状态
        if(chartById.getStatus().equals(StringEnum.running)) {
            handlerChartUpdateError(chartById.getId(), "请勿重复提交");
            throw new Exception("请勿重复提交");
        }
        //提交任务后，将数据库中相应任务改成执行态
        chartById.setStatus(StringEnum.running);
        boolean updatedById = chartService.updateById(chartById);
        if (!updatedById) {
            handlerChartUpdateError(chartById.getId(), "更新任务为执行态失败");
            throw new Exception("更新任务为执行态失败");
        }
        //图表可视化代码
        String chartCode = chartManager.doChat(q);
        //保存历史记录供获取分析数据结果
        Map<String, String> hisMap = new HashMap<>();
        hisMap.put("提问", message);
        hisMap.put("回答", chartCode);
        //分析结果
        String analys = chartManager.doAnalys(goal, hisMap);
        //todo rabbitmq 此处重传判断可改为 生成的代码是否符合echarts v5 ， 不符合则重传(此种方式更能用的上重传)
        chartById.setGenChart(chartCode);
        chartById.setGenResult(analys);
        chartById.setStatus(StringEnum.succeed);
        boolean succeedResult = chartService.updateById(chartById);
        if (!succeedResult){
            handlerChartUpdateError(chartById.getId(), "更新任务为成功态失败");
            throw new Exception("更新任务为成功态失败");
        }
    }
    private void handlerChartUpdateError(long chartId, String errorMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setExeMessage(errorMessage);
    }
}
